/*
 * 这个例子是想知道把vector/list中的元素以指针的形式放在外面用，当vector/list增加或减少元素时，指针所指向的内容是否变化？
 *
 * 结果： vector 有变化，而list无变化。
 *
 * PS 通过这个程序还可以看出: 
 * 1. vector 容量以2^n的方式增加。当容量增加时，原来的元素通过拷贝构造函数初始化。(不是每个版本都一样。g++中是这个实现)
 * 2. vector 中删除一个元素是通过后面的元素依次向前赋值然后将最后一个元素删除来实现的。
 */
#include <stdio.h>
#include <iostream>
#include <vector>
#include <list>

using namespace std;

class Test
{
public:
	Test( int i ) :i(i) { print_message( "in construct" ); }
	~Test() { print_message( "in destruct" );}
	Test( const Test &t )
	{
		this->i = t.i;
		print_message( "in copy construct" );
	}
	Test &operator=( const Test &t )
	{
		cout << "assign " << t.i << " to " << this->i << endl;
		this->i = t.i;
		return *this;
	}

	void print_message( const char *msg )
	{
		cout << i << ":" << msg << endl;
	}

public:
	int i;
};

template < class T >
void print_item_addr( const T &t )
{
	size_t i = 0;
	for( typename T::const_iterator it = t.begin(); it != t.end(); i++, it++ ) {
		cout << i << ":" << &(*it) << " ";
	}
	cout << endl;
}

template < class T >
void remove_odd_item( T &t )
{
	size_t i = 0;
	for( typename T::iterator it = t.begin(); it != t.end(); i++ ) {
		if( 0 == i % 2 ) {
			it ++;
		}
		else {
			it = t.erase( it );
		}
	}
}

int main( int argc, char *argv[] )
{
	vector< Test > v;
	list< Test > l;

	cout << "====== insert vector =========" << endl;
	for( int i = 0; i < 10; i++ ) {
		v.push_back( i );
		// print_item_addr( v );
	}

	cout << "====== insert list =========" << endl;
	for( int i = 0; i < 10; i++ ) {
		l.push_back( i );
	}

	cout << "====== print vector addr =========" << endl;
	print_item_addr( v );
	cout << "====== print list addr =========" << endl;
	print_item_addr( l );

	cout << "====== remove_odd_item vector =========" << endl;
	remove_odd_item( v );	
	cout << "====== remove_odd_item list =========" << endl;
	remove_odd_item( l );	


	cout << "====== print vector addr =========" << endl;
	print_item_addr( v );
	cout << "====== print list addr =========" << endl;
	print_item_addr( l );

	return 0;
}
